package com.dingyuhang.controller;


import com.dingyuhang.bean.User;
import com.dingyuhang.common.TiebaException;
import com.dingyuhang.service.ReplyService;
import com.dingyuhang.service.TopicService;
import com.dingyuhang.service.UserService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * 用户
 * @author fuqiyu
 *
 */
@Controller
public class UserController {
	
	 public static final String LOGIN_USER = "LOGIN_USER";

	@Autowired
	private UserService userService;
	
	@Autowired
    private TopicService topicService;
	
	@Autowired
    private ReplyService replyService;
	
	/**
	 * 首页--最新用户
	 * @param pageNum
	 * @param m
	 * @return
	 */
	@RequestMapping("/users")
	public String selectUsers(@RequestParam(defaultValue="1")Integer pageNum,Model m) {
		PageInfo<User> pageInfo= userService.selectUsers(pageNum);//分页查询
		m.addAttribute("pageInfo", pageInfo);
		return "user_new";
	}
	
	
	//跳转注册页面
	@GetMapping("/register")
	public String toRegister(Model model) {
		model.addAttribute("user", new User()); //绑定对象
		return "my/user_register";
	}
	
	/**
	 * 注册
	 * @param user
	 * @param result
	 * @param file
	 * @param model
	 * @return
	 */
	@PostMapping("/register")
	public String tegister(@Valid User user,BindingResult result,MultipartFile file,RedirectAttributes model) {
		try {
			user.validatePassword();//验证两次密码是否一致,不一致报错用catch判断是否走的是TiebaException异常
			user.validateCity();//验证三级联动是否选中
			userService.insertUser(user,file);//注册
			//注册成功，将用户名放在闪存中，解决redirect不能传递值的问题。
			model.addFlashAttribute("register_result", true);
            model.addFlashAttribute("userName", user.getUserName());
			return "redirect:/login"; //重定向到登陆方法
		} catch (TiebaException e) {
			result.rejectValue("userName", null, e.getMessage()); //验证密码是否一致
		}
		return "my/user_register";
	}


	//上传图片
	@ResponseBody
	@PostMapping("/register/upFile")
	public String upFile(MultipartFile file) throws IOException {
		System.out.println("===============================");
		if(file!=null){
			String path = "d:/img/";
			String originalFilename = file.getOriginalFilename();
			String fileName = UUID.randomUUID()+originalFilename.substring(originalFilename.lastIndexOf("."));
			File f = new File(path, fileName);
			file.transferTo(f);
			return "/img/"+fileName;
		}
		return null;
	}


	/**
	 * 跳转到登录页面
	 * @param user
	 * @param model
	 * @return
	 */
	@GetMapping("/login")
	public String login(User user,Model model) {
		if(model.containsAttribute("register_result")) {//判断是否注册和功成功后跳转过来的
			  model.addAttribute("message", "注册成功，请登录！"); //页面提示注册成功
			  String uname = (String) model.asMap().get("userName");//获取注册时的用户名
			  user.setUserName(uname);
			  model.addAttribute("user", user);
		}
		return "my/user_login";
	}
	
	
	/**
	 * 登陆 
	 */
    @PostMapping("/login")
    public String login1(User user, Model model, HttpSession session){
        try {
             user = userService.login(user);   //开始登录
            session.setAttribute("LOGIN_USER", user);
            return "redirect:index";  //重定向到贴吧首页
        }
        catch (TiebaException e){
            model.addAttribute("message", e.getMessage());
        }
        return "my/user_login";
    }
    
    
    /**
       *   注销
     * @param session
     * @return
     */
    @GetMapping("/logout")
    public String logout(HttpSession session){
        session.invalidate();
        return "redirect:/login";
    }
    
    /**
     	* 点击姓名的时候显示的首页
     * @param model
     * @param session
     * @return
     */

    @GetMapping("/my/index")
    public String my(Model model, HttpSession session){
        User user = (User) session.getAttribute("LOGIN_USER");//获取登陆人信息
        int myTopics = topicService.countTopics(user.getId());
        int myReplies = replyService.countReply(user.getId());
        model.addAttribute("myTopics", myTopics);
        model.addAttribute("myReplies", myReplies);
        return "my/index";
    }
    
    
    /**
      * 个人设置
     */
    @GetMapping("/my/info")
    public String  userInfo(HttpSession session,Model model) {
    	 User user = (User) session.getAttribute("LOGIN_USER");//获取登陆人信息
    	 model.addAttribute("user", user); //页面绑定
		return "my/user_info";
    }  
    
    /**
     	* 个人设置==========>修改
     * @param user
     * @param result
     * @param file
     * @param model
     * @return
     */
	@PostMapping("/update")
	public String updateUser(@Valid @ModelAttribute("user")User user,BindingResult result,MultipartFile file,HttpSession session) {
		try {
			user.validateCity();//验证三级联动是否选中
			userService.updateUser(user,file);//修改
			session.setAttribute("LOGIN_USER", userService.getUserById(user.getId()));//修改成功将以前的session替换掉
			return "redirect:/my/index"; //重定向到登陆方法
		} catch (TiebaException e) {
			result.rejectValue("userName", null, e.getMessage()); //验证密码是否一致
		}catch (Exception e) {
			e.printStackTrace();
		}
		return "my/user_register";
	}
	
	/**
	 * 去修改密码页面
	 * @return
	 */
	@GetMapping("/my/update/password")
	public String toUpdatePwd(Model model,HttpSession session) {
		model.addAttribute("user", (User) session.getAttribute("LOGIN_USER"));
		return "my/user_update_pass";
	}
	
	
	/**
	 * 修改密码
	 */
	@PostMapping("/my/update/password")
	public String updatePwd(@Valid @ModelAttribute("user")User user,BindingResult result, Model model,HttpSession session) {
		try {
			 user.validatePassword();//验证两次密码是否一致
				 User sessionUser =  (User) session.getAttribute("LOGIN_USER");//获取登陆人信息  
				 if(!user.getOldPassword().equals(sessionUser.getPassword())){
					 result.rejectValue("oldPassword", null, "老密码错误");
		         }
			if(!result.hasErrors()) {
				  sessionUser.setPassword(user.getPassword());
				  userService.updateUser(sessionUser, null); //修改
				   //清空Session中的数据
		            session.invalidate();
		            //重新登录
		            model.addAttribute("message", "密码修改成功，点这里重新<a href='/login'>登录</a>");
		            return "my/pass_ok";
			}	 
		} catch (TiebaException e) {
			result.rejectValue("userName", null, e.getMessage()); //验证密码是否一致
		}
		return "my/user_update_pass";
	}
}
